package me.hys.service.resource.impl;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import me.hys.base.PageQuery;
import me.hys.bo.resource.CaseBo;
import me.hys.dao.resource.ICaseMapper;
import me.hys.entity.resource.CaseEntity;
import me.hys.kits.HtmlKit;
import me.hys.service.resource.ICaseManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Author: @author HYS . <br>
 * Date: 2015-9-19 下午2:35:27 . <br>
 * Function: 案例
 */
@Service
@Transactional
class CaseManagerImpl implements ICaseManager {
	@Autowired
	private ICaseMapper caseMapper;

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.base.IBaseManager#delete(java.lang.String)
	 */
	@Override
	public void delete(String id) {
		caseMapper.delete(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.base.IBaseManager#findByCond(java.util.Map)
	 */
	@Override
	public List<CaseEntity> findByCond(Map<String, Object> cond) {
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.base.IBaseManager#findById(java.lang.String)
	 */
	@Override
	public CaseEntity findById(String id) {
		return caseMapper.findById(id);
	}

	@Override
	public CaseBo findLatest() {
		return caseMapper.findLatest();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.base.IBaseManager#findPage(me.hys.base.PageQuery)
	 */
	@Override
	public PageQuery<CaseEntity> findPage(PageQuery<CaseEntity> page) {
		List<CaseEntity> list = caseMapper.findAll(page.getCondition());
		for (CaseEntity entity : list) {
			entity.setContent(HtmlKit.filterSubstring(entity.getContent(),
					HtmlKit.LENGTH));
		}
		page.setList(list);
		page.setTotal(caseMapper.findAllCount(page.getCondition()));
		// 总页数
		int size = (int) Math.ceil(page.getTotal() * 1.0f / page.getLimit());
		page.setSize(size);
		return page;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * me.hys.service.resource.ICaseManager#findPageBo(me.hys.base.PageQuery)
	 */
	@Override
	public PageQuery<CaseBo> findPageBo(PageQuery<CaseBo> page) {
		List<CaseBo> list = caseMapper.findAllBo(page.getCondition());
		for (CaseBo entity : list) {
			entity.setContent(HtmlKit.filterSubstring(entity.getContent(), 50));
		}
		page.setList(list);
		page.setTotal(caseMapper.findAllCount(page.getCondition()));
		// 总页数
		int size = (int) Math.ceil(page.getTotal() * 1.0f / page.getLimit());
		page.setSize(size);
		return page;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.base.IBaseManager#saveOrUpdate(java.lang.Object)
	 */
	@Override
	public int saveOrUpdate(CaseEntity entity) {
		if (entity.getId() > 0) {
			return caseMapper.update(entity);
		} else {
			entity.setPubtime(new Timestamp(System.currentTimeMillis()));
			caseMapper.save(entity);
			return entity.getId();
		}
	}
}
